package chooongg.base.utils

import android.app.Activity
import android.app.Service
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.pm.PackageManager
import chooongg.base.Utils

object MetaDataUtils {

    /**
     * 在Application下获取MetaData数据
     */
    fun getMetaDataInApp(key: String): Any? {
        return try {
            val ai = Utils.app.packageManager.getApplicationInfo(
                Utils.app.packageName,
                PackageManager.GET_META_DATA
            )
            ai.metaData.get(key)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 在Activity下获取MetaData数据
     */
    fun getMetaDataInActivity(clazz: Class<out Activity>, key: String): Any? {
        val pm = Utils.app.packageManager
        val componentName = ComponentName(Utils.app, clazz)
        return try {
            val ai = pm.getActivityInfo(componentName, PackageManager.GET_META_DATA)
            ai.metaData.get(key)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 在Service下获取MetaData数据
     */
    fun getMetaDataInService(clazz: Class<out Service>, key: String): Any? {
        val pm = Utils.app.packageManager
        val componentName = ComponentName(Utils.app, clazz)
        return try {
            val ai = pm.getActivityInfo(componentName, PackageManager.GET_META_DATA)
            ai.metaData.get(key)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    /**
     * 在Receiver下获取MetaData数据
     */
    fun getMetaDataInReceiver(clazz: Class<out BroadcastReceiver>, key: String): Any? {
        val pm = Utils.app.packageManager
        val componentName = ComponentName(Utils.app, clazz)
        return try {
            val ai = pm.getActivityInfo(componentName, PackageManager.GET_META_DATA)
            ai.metaData.get(key)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }
}